package com.google.code.p.restrpc.client.proxy;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.parser.ParserConfig;
import com.google.code.p.restrpc.RpcException;
import com.google.code.p.restrpc.RpcResponse;
import com.google.code.p.restrpc.client.RpcResponseHandler;

/**
 * @author dz
 */
public class DefaultRpcResponseHandler implements RpcResponseHandler {
    
    public static final DefaultRpcResponseHandler instance = new DefaultRpcResponseHandler();
    
    /**
     * 
     */
    public Object handle(RpcResponse response, Class clazz) throws RpcException {
        if (response.getFault() != null) {
            if (response.getFault().isBizError()) {
                throw new RpcBizException(response.getFault().getMessage(),
                                          response.getFault().getCode(),
                                          response.getFault().getDetail());
            }
            else {
                throw new RpcInvokeException(response.getFault().getMessage(),
                                             response.getFault().getCode(),
                                             response.getFault().getDetail());
            }
        }
        if (ParserConfig.getGlobalInstance().isPrimitive(clazz)) {
            return response.getResult();
        }
        
        Object result = response.getResult();
        if (result == null) {
            return null;
        }
        if (result instanceof JSON) {
            return JSON.toJavaObject((JSON) result, clazz);
        }
        return result;
    }
    
}
